/* eslint-disable eqeqeq */
import Card from '@/components/Card';
import Description from '@/components/Description';
import type { ProColumns } from '@/components/Pro';
import { ProTable } from '@/components/Pro';
import {
  monitorServerControllerComponentPage,
  monitorServerControllerServerRealTime,
} from '@/services/ess/alertConfig';
import { Button, Flex, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';
import styles from '../index.less';

interface BaseInfoProps {
  id: string;
  onBack: () => void;
}

const BaseInfo: React.FC<BaseInfoProps> = ({ id, onBack }) => {
  const intl = useIntl();
  const [serverData, setServerData] = useState<API.MonitorServerDTO | null>(null);

  useEffect(() => {
    const fetchServerData = async () => {
      try {
        const response = await monitorServerControllerServerRealTime({
          serverId: parseInt(id, 10),
        });
        if (response.success && response.data) {
          setServerData(response.data);
        }
      } catch (error) {
        console.error('Error fetching server data:', error);
      }
    };

    fetchServerData();
  }, [id]);

  const systemResourcesData = serverData
    ? [
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.cpu' }),
          value: serverData.cpuModel ?? '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.cpuUsagePercentage' }),
          value:
            serverData.monitorData?.cpuUsedPer != null
              ? `${serverData.monitorData.cpuUsedPer}%`
              : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.cpuTemperature' }),
          value:
            serverData.monitorData?.cpuTemp != null ? `${serverData.monitorData.cpuTemp}℃` : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.totalMemory' }),
          value:
            serverData.monitorData?.totalMemory != null
              ? `${serverData.monitorData.totalMemory}G`
              : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.usedMemory' }),
          value:
            serverData.monitorData?.memoryUsed != null
              ? `${serverData.monitorData.memoryUsed}G`
              : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.memoryUsagePercentage' }),
          value:
            serverData.monitorData?.memoryUsedPer != null
              ? `${serverData.monitorData.memoryUsedPer}%`
              : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.totalDiskSpace' }),
          value:
            serverData.monitorData?.totalDisk != null
              ? `${serverData.monitorData.totalDisk}G`
              : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.usedDiskSpace' }),
          value:
            serverData.monitorData?.diskUsed != null ? `${serverData.monitorData.diskUsed}G` : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.diskUsagePercentage' }),
          value:
            serverData.monitorData?.diskUsedPer != null
              ? `${serverData.monitorData.diskUsedPer}%`
              : '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.internalIP' }),
          value: serverData.monitorData?.ip1 ?? '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.publicIP' }),
          value: serverData.monitorData?.ip2 ?? '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.osVersion' }),
          value: serverData.os ?? '--',
        },
        {
          label: intl.formatMessage({ id: 'remoteUpgrade.osKernelVersion' }),
          value: serverData.osKernel ?? '--',
        },
      ].map((item) => ({ ...item, children: item.value }))
    : [];
  const databaseTypeMap = {
    0: 'mysql',
    1: 'dm',
    2: 'oracle',
    3: 'redis',
    4: 'tdengine',
  };

  const getStatusDisplay = (runStatus: number | string | null | undefined) => {
    if (runStatus === null || runStatus === undefined) {
      return '--';
    }
    return runStatus === 1
      ? intl.formatMessage({ id: 'remoteUpgrade.running' })
      : intl.formatMessage({ id: 'remoteUpgrade.stop' });
  };
  const databaseResourcesData = serverData?.databaseList
    ? serverData.databaseList.flatMap((db) => {
        const databaseType =
          databaseTypeMap[db.databaseType as unknown as keyof typeof databaseTypeMap] || 'unknown';
        const status = getStatusDisplay(db.runStatus);
        return [
          {
            label: intl.formatMessage({ id: `remoteUpgrade.${databaseType}Status` }),
            value: status,
            children: status,
          },
          {
            label: intl.formatMessage({ id: `remoteUpgrade.${databaseType}Version` }),
            value: db.databaseVersion ?? '--',
            children: db.databaseVersion ?? '--',
          },
        ];
      })
    : [];

  const componentColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgrade.componentNo' }),
      dataIndex: 'index',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgrade.componentName' }),
      dataIndex: 'componentName',
      key: 'componentName',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgrade.runningStatus' }),
      dataIndex: 'runStatus',
      key: 'runStatus',
      render: (_, record) => getStatusDisplay(record.runStatus),
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgrade.componentVersion' }),
      dataIndex: 'componentVersion',
      key: 'componentVersion',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgrade.updateTime' }),
      dataIndex: 'updatedTime',
      key: 'updatedTime',
    },
  ];

  return (
    <div className={styles.baseInfoContainer}>
      <div className={styles.systemResourceStatus}>
        <Flex justify="" align="center">
          <Typography.Text
            style={{ fontSize: 18, fontWeight: 600, color: 'rgba(34, 34, 34, 0.88)' }}
          >
            {intl.formatMessage({ id: 'remoteUpgrade.systemResourceStatus' })}
          </Typography.Text>
          <Button onClick={onBack} type="link">
            {intl.formatMessage({ id: 'remoteUpgrade.back' })}
          </Button>
        </Flex>
        <Description items={systemResourcesData} column={4} />
      </div>
      <div className={styles.detailContainerCardBound}></div>
      <Card
        title={intl.formatMessage({ id: 'remoteUpgrade.databaseResourceStatus' })}
        bordered={false}
        className={styles.detailContainerCard}
      >
        <Description items={databaseResourcesData} column={4} />
      </Card>
      <div className={styles.detailContainerCardBound}></div>
      <Card
        title={intl.formatMessage({ id: 'remoteUpgrade.componentResourceStatus' })}
        bordered={false}
        className={styles.detailContainerCard}
      >
        <ProTable
          columns={componentColumns}
          request={async (params) => {
            const { current, pageSize } = params;
            const response = await monitorServerControllerComponentPage({
              serverId: parseInt(id, 10),
              current: current ?? 1,
              pageSize: pageSize ?? 10,
            });
            if (response.success && response.data) {
              return {
                data: response.data.records || [],
                success: true,
                total: response.data.total,
              };
            }
            return {
              data: [],
              success: false,
              total: 0,
            };
          }}
          search={false}
          pagination={{
            showSizeChanger: true,
          }}
        />
      </Card>
    </div>
  );
};

export default BaseInfo;
